package com.abeir.bilibili;

import com.abeir.bilibili.cmmand.CommanderManager;
import com.abeir.bilibili.convert.DefaultConvertFactory;
import com.abeir.bilibili.convert.FfmpegMerger;
import com.abeir.bilibili.detection.FullFolderDetector;

import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;

public class Application {

    private final CommanderManager commanderManager;
    private FfmpegMerger merger;

    public Application(){
        commanderManager = new CommanderManager("bilibili_tools");
    }

    public void exec(String[] args) throws Exception {
        if(!commanderManager.parse(args)){
            return;
        }

        merger = FfmpegMerger.newBuilder()
                .setFfmpeg(Path.of(commanderManager.getFfmpeg()))
                .setTempDirectory(Path.of(commanderManager.getTemporary()))
                .setOutDirectory(Path.of(commanderManager.getOutput()))
                .setEnableOutputConsole(true)
                .build();
        doFull(Path.of(commanderManager.getInput()));
    }

    private void doFull(Path root) throws Exception {
        FullFolderDetector detector = new FullFolderDetector(root);
        List<Path> dirs = detector.detect();
        for(Path origin : dirs){
            Optional<File> result = convert(origin);
            result.ifPresent(System.out::println);
        }
    }

    private Optional<File> convert(Path origin) throws Exception {
        DefaultConvertFactory factory = new DefaultConvertFactory(origin);
        factory.setVideoFilenameSuffixes(commanderManager.getVideoSuffixes());
        factory.setAudioFilenameSuffixes(commanderManager.getAudioSuffixes());
        return factory.convert(merger);
    }


    public static void main(String[] args) throws Exception {

//        args = new String[] { "-i", "D:\\Downloads\\bilibili_4",
//                "-o", "D:\\Downloads\\bilibili_4_out",
//                "-f", "D:\\software\\Scoop\\App\\shims\\ffmpeg.exe",
//                "-vs", "100048.m4s",
//                "-vs", "100101.m4s"
//        };

        Application app = new Application();
        app.exec(args);

    }
}
